package com.cat.chapter051;

import java.util.Arrays;

/**
 * @author cat
 * @description https://leetcode.cn/problems/find-k-th-smallest-pair-distance/
 * @create 2025/7/22 11:31
 * @since JDK17
 */

public class Solution04 {
    static int N = ((int) (1e6 + 10));
    public boolean check(int[] nums, int k, int cur) {
        int cnt = 0;
        for (int i = 0, j = 1; j < nums.length; j++) {
            if (nums[j] - nums[i] <= cur) {
                cnt += j - i;
            } else {
                i++;
            }
            if (cnt >= k) {
                return true;
            }
        }
        return false;
    }
    public int smallestDistancePair(int[] nums, int k) {
        Arrays.sort(nums);  // 排升序
        int n = nums.length, l = 0, mid, r = nums[n - 1] - nums[0] + 1;
        while (l + 1 < r) {
            mid = l + (r - l) / 2;
            if (check(nums, k, mid)) {  // 成立说明这个数字可以更小
                r = mid;
            } else {
                l = mid;
            }
        }
        return r;
    }
}
